<?php require_once('PhpSerial.php');
$PhpSerial=new PhpSerial;$PhpSerial->deviceSet('COM3');
if($PhpSerial->deviceOpen()){
    $PhpSerial->sendMessage("AT+CMGF=1\n");
    $out=$PhpSerial->readPort();
    if(strpos($out,"OK")!==false){
        $PhpSerial->sendMessage("AT+CMGR=1\n",2);
        $inbox=$PhpSerial->readPort();
        if($inbox!=='AT+CMGR=1\nERROR'){
            $inbox=preg_replace(array("/\r|\nOK|\+CMTI: \"SM\",[0-9]/"),"",$inbox);
            $arr=explode("+CMGR:",$inbox);
            if(count($arr)>=2){
                $fields=preg_split('/\r|\n/',$arr[1],2);
                $headArr=explode(',',$fields[0]);
                if(count($headArr)>=3){
                    $sender=str_replace(array('+','"',','),'',$headArr[1]);
                    $date='20'.str_replace('"','',$headArr[3]);
                    $time=substr($headArr[4],0,8);
                    $msg=preg_replace('/[^(\x20-\x7F)]*/','',$fields[1]);
                    try{
                        $dbconn=pg_connect("host=localhost port=5432 dbname=sms user=postgres password=admin");
                        pg_query_params($dbconn,"select in_insert($1,$2,$3,$4,$5)",array($sender,'84905000706',$msg,$date,$time));
                        $PhpSerial->sendMessage("AT+CMGD=1\r");
                    }
                    catch(Exception $e){
                    }
                }
            }
        }
    }
}
$PhpSerial->deviceClose();
?>